<?php

namespace Admin\Controller;

class DockWeightController extends AdminController {

    public function index() {

        $keywords = I('keywords');
        $where['dw.is_del'] = 0;
        if ($keywords) {
            $where['p.port_name'] = array('like', "%{$keywords}%");
            $this->assign('keywords', $keywords);
        }

        $M = M()->table("ot_dock_weight as dw")
                ->join('ot_port AS p on dw.port_id = p.port_id');
        $field = 'dw.*,p.port_name';
        $order = "dw.weight_id desc";
        $list = $this->lists($M, $where, $order, $field);

        $this->assign('_list', $list);
        $this->display();
    }

    public function add() {
        $weight_id = I('id', 0, 'intval');
        if (IS_POST) {
            $port_id = I('port_id', 0, 'intval');
            $weight_desc = I('weight_desc');
            $weight_price = I('weight_price', 0);

            if ($port_id == 0) {
                $this->error('必须选择港口');
            }

            if (empty($weight_desc)) {
                $this->error('货重描述必须填写');
            }

            $data['port_id'] = $port_id;
            $data['weight_desc'] = $weight_desc;
            $data['weight_price'] = $weight_price;

            $result = 0;
            if ($weight_id == 0) {
                $result = M('DockWeight')->add($data);
            } else {
                $result = M('DockWeight')->where(['weight_id' => $weight_id])->save($data);
            }

            if ($result) {
                $this->success('操作成功', U('index'));
            } else {
                $this->error('操作失败');
            }
        } else {

            if ($weight_id != 0) {
                $data = M('DockWeight')->where(array('weight_id' => $weight_id))->find();
                $this->assign('data', $data);
            }

            $plist = M('Port')->where(['is_del' => 0])->select();
            $this->assign('dlist', $plist);
            $this->display();
        }
    }

    public function del() {
        $weight_id = I('id', 0, 'intval');
        if ($weight_id == 0) {
            $this->error('请选择删除项');
        }

        $res = M('DockWeight')->where(array('weight_id' => $weight_id))->save(['is_del' => 1]);

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}
